package com.zzj.controller;

import cn.hutool.core.lang.id.NanoId;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzj.base.Result;
import com.zzj.entity.Invitation;
import com.zzj.model.api.InvitationApi;
import com.zzj.model.dto.InvitationCreateDTO;
import com.zzj.model.dto.QueryListDTO;
import com.zzj.service.IInvitationService;
import com.zzj.service.RedisService;
import com.zzj.utils.QueryUtil;
import com.zzj.utils.Utils;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-05-12
 */
@RestController
@RequestMapping("/invitation")
public class InvitationController implements InvitationApi {

    @Resource
    private IInvitationService invitationService;
    @Resource
    private RedisService redisService;

    /**
     * 条件查询
     * @param in
     * @return
     */
    @Transactional
    @PostMapping("list")
    public Result list(@RequestBody @Validated QueryListDTO in) {
        QueryWrapper<Invitation> queryWrapper = QueryUtil.paramsWrapper(in.getAndParams(), in.getOrParams(), in.getOrderParams());
        Page<Invitation> invitationPage = new Page<>(in.getPageNo(), in.getPageSize());
        IPage<Invitation> invitationIPage = invitationService.getBaseMapper().selectPage(invitationPage, queryWrapper);
        return Result.success(invitationIPage);
    }

    /**
     * 创建邀请码
     * @param in
     * @return
     */
    @Transactional
    @PostMapping("create")
    public Result create(@RequestBody @Validated InvitationCreateDTO in) {
        Invitation invitation = invitationService.create(in);
        redisService.createInvitation(invitation.getCode(), String.valueOf(in.getType()),in.getDuration());
        return Result.success("创建成功",invitation.getCode());
    }

    /**
     * 销毁邀请码
     * @param code
     * @return
     */
    @Transactional
    @PostMapping("expire")
    public Result expire(@RequestParam String code) {
        boolean update = invitationService.lambdaUpdate().eq(Invitation::getCode, code)
                .set(Invitation::getStatus, 2).update();
        invitationService.expire(code);
        redisService.removeInvitation(code);
        return Result.success("销毁成功");
    }

    /**
     * 使用邀请码
     * @param code
     * @return
     */
    @Transactional
    @Override
    public boolean use(String code) {
        redisService.removeInvitation(code);
        return invitationService.use(code);
    }

}
